package org.dromara.web.appInterface;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.dromara.app.appParams.*;
import org.dromara.app.appReturn.AppDictionaryReturn;
import org.dromara.app.appReturn.AppMyUserInfo;
import org.dromara.app.appReturn.AppPriceLogRetuen;
import org.dromara.app.appReturn.AppUserHomePageReturn;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.app.domain.SkAppUser;
import org.dromara.app.domain.bo.SkAppUserBo;
import org.dromara.app.domain.vo.SkAppUserVo;
import org.dromara.app.service.ISkAppUserService;
import org.dromara.app.service.ISkFansUserService;
import org.dromara.app.service.ISkPriceLogService;
import org.dromara.app.service.ISkWithdrawalLogService;
import org.dromara.common.core.domain.R;
import org.dromara.system.domain.SysDictData;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysConfigService;
import org.dromara.system.service.ISysDictDataService;
import org.dromara.system.service.ISysOssService;
import org.dromara.web.CssUtil.CssOrderServer;
import org.dromara.web.CssUtil.CssTiXianServer;
import org.dromara.web.CssUtil.payUtil.bean.AllocateAccountQueryOut;
import org.dromara.web.CssUtil.payUtil.bean.OpenAccountOut;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Tag(name = "我的页面相关接口")
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/my")
@SaIgnore
public class AppMyInterface {

    private final ISkAppUserService iSkAppUserService;

    private final ISysOssService iSysOssService;
    private final ISkPriceLogService iSkPriceLogService;

    private final ISkWithdrawalLogService iSkWithdrawalLogService;

    private final CssOrderServer cssOrderServer;

    private final ISkFansUserService iSkFansUserService;

    private final ISysConfigService iSysConfigService;

    private final CssTiXianServer cssTiXianServer;
    /**
     * 图片上传
     */
    @PostMapping("/upload")
    @Operation(summary = "图片上传", method = "post")
    public R<SysOssVo> upload(@RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        SysOssVo oss = iSysOssService.upload(file);
        return R.ok(oss);
    }

    /**
     * 上传语音
     */
    @PostMapping("/uploadvideo")
    @Operation(summary = "上传语音", method = "post")
    public R<SysOssVo> uploadvideo(@RequestPart("file") MultipartFile file,HttpServletRequest req) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        SysOssVo oss = iSysOssService.upload(file);
        iSkAppUserService.uploadvideo(oss.getUrl(),req);
        return R.ok(oss);
    }

    /**
     * 我的页面个人信息
     *
     * @param req
     * @return
     */
    @PostMapping("/getMyInfo")
    @Operation(summary = "我的页面个人信息", method = "post")
    public R<AppMyUserInfo> getProjectCategory(HttpServletRequest req) {
        AppMyUserInfo app = iSkAppUserService.getMyInfo(req);
        //判断是否是会员，根据会员类型查询折扣
        String zhekou = null;
        if(app.getVipType().longValue()>0){
            if(app.getVipType().longValue()==1){
                zhekou = iSysConfigService.selectConfigByKey(CssUtils.getHuiYuanConfig("白银下单享受折扣优惠").toString());
            }
            if(app.getVipType().longValue()==2){
                zhekou = iSysConfigService.selectConfigByKey(CssUtils.getHuiYuanConfig("黄金下单享受折扣优惠").toString());
            }
            if(app.getVipType().longValue()==3){
                zhekou = iSysConfigService.selectConfigByKey(CssUtils.getHuiYuanConfig("钻石下单享受折扣优惠").toString());
            }
        }
        app.setZhekou(zhekou);
        //新增 VIP按钮控制
        String isVip = iSysConfigService.selectConfigByKey("kai_tong_vip_an_niu");
        String isYueDan = iSysConfigService.selectConfigByKey("yuan_dan_an_niu");
        app.setIsVip(isVip);
        app.setIsYueDan(isYueDan);
        // 获取邀请人数
        // 邀请人数
        Long yqNumber = 0L;
        // 邀请达人人数
        Long yqDarenNumber = 0L;
        SkAppUserBo bo = new SkAppUserBo();
        if(app.getIsHehuo() != null && app.getIsHehuo() == 1L){
            yqNumber = iSkAppUserService.countInvitations(app.getUserId());
            yqDarenNumber = iSkAppUserService.countDarenInvitations(app.getUserId());
        }else if(app.getIsTgDaren() != null && app.getIsTgDaren() == 1L){
            bo.setYqUserId(app.getUserId());
            List<SkAppUserVo> userList = iSkAppUserService.queryList(bo);
            yqNumber = Long.valueOf(userList.size());
            List<SkAppUserVo> darenList = userList.stream().filter(e -> e.getUserType() == 2L).toList();
            yqDarenNumber = Long.valueOf(darenList.size());
        }
        app.setYqNumber(yqNumber);
        app.setYqDarenNumber(yqDarenNumber);
        return R.ok(app);
    }

    /**
     * 更改手机号码
     *
     * @param req
     * @return
     */
    @PostMapping("/updatePhone")
    @Operation(summary = "更改手机号码", method = "post")
    public R<AppMyUserInfo> updatePhone(@RequestBody AppUpdatePhoneParam params, HttpServletRequest req) {
        iSkAppUserService.updatePhone(params,req);
        return R.ok("更改成功");
    }

    /**
     * 设置交易密码
     */
    @PostMapping("/settingPayPassword")
    @Operation(summary = "设置交易密码", method = "post")
    public R settingPayPassword(@RequestBody AppSettingPayPasswordParams params, HttpServletRequest req) {
        iSkAppUserService.settingPayPassword(params,req);
        return R.ok("设置成功");
    }

    /**
     * 个人主页
     *
     * @param params
     * @param req
     * @return
     */
    @PostMapping("/getUserHomePage")
    @Operation(summary = "个人主页", method = "post")
    public R<AppUserHomePageReturn> getUserHomePage(@RequestBody AppHomePageParams params, HttpServletRequest req) {
        AppUserHomePageReturn app = iSkAppUserService.getUserHomePage(params,req);
        return R.ok(app);
    }

    /**
     * 编辑个人资料
     *
     * @param params
     * @param req
     * @return
     */
    @PostMapping("/updateUserInfo")
    @Operation(summary = "编辑个人资料", method = "post")
    public R<AppUserHomePageReturn> updateUserInfo(@RequestBody AppUpdateUserInfoParams params, HttpServletRequest req) throws Exception {
        iSkAppUserService.updateUserInfo(params,req);
        return R.ok("更新成功");
    }

    /**
     * 字典查询
     */
    @PostMapping("/getDictionary")
    @Operation(summary = "字典查询", method = "post")
    public R<List<AppDictionaryReturn>> getDictionary(@RequestBody AppDictionaryParam params, HttpServletRequest req) throws Exception {
        List<AppDictionaryReturn> list = iSkAppUserService.getDictionary(params,req);
        return R.ok(list);
    }

    /**
     * 钱包余额
     */
    @PostMapping("/getBalance")
    @Operation(summary = "钱包余额", method = "post")
    public R<BigDecimal> getBalance( HttpServletRequest req) throws Exception {
        BigDecimal balance = iSkAppUserService.getBalance(req);
        return R.ok(balance);
    }

    /**
     * 金额日志
     */
    @PostMapping("/getPriceLog")
    @Operation(summary = "金额日志", method = "post")
    public R<List<AppPriceLogRetuen>> getPriceLog(@RequestBody AppPageParams params, HttpServletRequest req) throws Exception {
        List<AppPriceLogRetuen> list = iSkPriceLogService.getPriceLog(params,req);
        return R.ok(list);
    }


    /**
     * 申请提现
     */
    @PostMapping("/applyForWithdrawal")
    @Operation(summary = "申请提现", method = "post")
    public R<List<AppPriceLogRetuen>> applyForWithdrawal(@RequestBody AppApplyForWithdrawalParams params, HttpServletRequest req) throws Exception {
        iSkWithdrawalLogService.applyForWithdrawal(params,req);
        SkAppUser skAppUser = iSkAppUserService.getUserById(CssUtils.getUserId(req));
        cssOrderServer.activeAccount(skAppUser,params.getPrice().negate(),4L,"提现");
        return R.ok("申请成功");
    }

    /**
     * 更改照片
     * @param params
     * @param req
     * @return
     * @throws Exception
     */
    @PostMapping("/updateUserPhoto")
    @Operation(summary = "更改照片", method = "post")
    public R updateUserPhoto(@RequestBody AppUpdateUserInfoParams params, HttpServletRequest req) throws Exception {
        iSkAppUserService.updateUserPhoto(params,req);
        return R.ok("更新成功");
    }

    /**
     * 更改视频
     * @param req
     * @return
     * @throws Exception
     */
    @PostMapping("/updateVideo")
    @Operation(summary = "更改视频", method = "post")
    public R<SysOssVo> updateVideo(@RequestPart("file") MultipartFile file,HttpServletRequest req) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        SysOssVo oss = iSysOssService.upload(file);
        iSkAppUserService.updateVideo(oss.getUrl(),req);
        return R.ok(oss);
    }

    /**
     * 达人上下班
     */
    @PostMapping("/commuting")
    @Operation(summary = "达人上下班", method = "post")
    public R commuting(@RequestBody AppCommutingParams params, HttpServletRequest req) throws Exception {
        iSkAppUserService.commuting(params,req);
        return R.ok("更新成功");
    }

    /**
     * 实名认证
     */
    @PostMapping("/realNameAuthentication")
    @Operation(summary = "实名认证", method = "post")
    public R realNameAuthentication(@RequestBody AppRealNameAuthenticationParam params, HttpServletRequest req) throws Exception {
        iSkAppUserService.realNameAuthentication(params,req);
        return R.ok("更新成功");
    }

    /**
     * 获取设备ID
     */
    @PostMapping("/getSheBeiId")
    @Operation(summary = "获取设备ID", method = "post")
    public R<AppMyUserInfo> getSheBeiId(@RequestBody AppUserIdParam params, HttpServletRequest req) throws Exception {
        AppMyUserInfo app = iSkAppUserService.getSheBeiId(params,req);
        return R.ok(app);
    }

    /**
     * 获取位置信息
     */
    @PostMapping("/getLocation")
    @Operation(summary = "获取位置信息", method = "post")
    public R<JSON> getLocation(@RequestBody AppLocation params, HttpServletRequest req) throws Exception {
        String json = iSkAppUserService.getLocation(params,req);
        return R.ok(JSONUtil.parse(json));
    }

    /**
     * 绑定提现账户
     */
    @PostMapping("/bindWithdrawalAccount")
    @Operation(summary = "绑定提现账户", method = "post")
    public R<OpenAccountOut> bindWithdrawalAccount(@RequestBody AppBindWithdrawalAccountParams params, HttpServletRequest req) throws Exception {
        OpenAccountOut createTiXian = cssTiXianServer.createTiXian(params);
        iSkAppUserService.bindWithdrawalAccount(params,createTiXian.getAccountIn(),req);
        return R.ok("请求成功",createTiXian);
    }

    /**
     * 获取提现账户信息
     *
     * @param req
     * @return
     * @throws Exception
     */
    @PostMapping("/getWithdrawalAccount")
    @Operation(summary = "获取提现账户信息", method = "post")
    public R<AppBindWithdrawalAccountParams> getWithdrawalAccount( HttpServletRequest req) throws Exception {
        AppBindWithdrawalAccountParams accountIn = iSkAppUserService.getWithdrawalAccount(req);
        return R.ok("请求成功",accountIn);
    }

    /**
     * 解绑提现账户
     */
    @PostMapping("/unbindWithdrawalAccount")
    @Operation(summary = "解绑提现账户", method = "post")
    public R<Void> unbindWithdrawalAccount( HttpServletRequest req){
        try {
            Long userId = CssUtils.getUserId(req);
            SkAppUser skAppUser = iSkAppUserService.getUserById(userId);
            Element root = cssTiXianServer.delTiXian(skAppUser);
            if (root != null) {
                String resCode = getNodeValue(root,"respCode");
                if ("0000".equals(resCode)) {
                    return R.ok("请求成功");
                }else{
                    throw new RuntimeException(getNodeValue(root,"respDesc"));
                }
            }else {
                throw new RuntimeException("未查询到相关信息");
            }
        }catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 解绑提现账户
     * @return
     */
    @PostMapping("/delWithdrawalAccount")
    @Operation(summary = "解绑提现账户", method = "post")
    public R<Void> delWithdrawalAccount( HttpServletRequest req){
        try {
            Long userId = CssUtils.getUserId(req);
            SkAppUser skAppUser = iSkAppUserService.getUserById(userId);
            if (skAppUser != null) {
                //查询是否有效
                Map<String,Object> map = cssTiXianServer.selectIsCunZai(skAppUser);
                if (map!=null && map.get("status")!=null && "02".equals(map.get("status"))){
                    Element root = cssTiXianServer.deleteWithdrawalAccount(skAppUser);
                    if (root != null) {
                        String resCode = getNodeValue(root,"respCode");
                        if ("0000".equals(resCode)) {
                            //解绑第三方
                            iSkAppUserService.unbindWithdrawalAccount(req);
                            return R.ok("请求成功");
                        }else{
                            throw new RuntimeException(getNodeValue(root,"respDesc"));
                        }
                    }else {
                        throw new RuntimeException("未查询到相关信息");
                    }
                }else{
                    Element root = cssTiXianServer.delTiXian(skAppUser);
                    if (root != null) {
                        String resCode = getNodeValue(root,"respCode");
                        if ("0000".equals(resCode)) {
                            return R.ok("请求成功");
                        }else{
                            throw new RuntimeException(getNodeValue(root,"respDesc"));
                        }
                    }else {
                        throw new RuntimeException("未查询到相关信息");
                    }
                }
            }
            return R.ok("请求成功");
        }catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @PostMapping("/deleteWithdrawalAccount")
    @Operation(summary = "删除有效提现账户", method = "post")
    public R<Void> deleteWithdrawalAccount( HttpServletRequest req){
        try {
            Long userId = CssUtils.getUserId(req);
            SkAppUser skAppUser = iSkAppUserService.getUserById(userId);
            Element root = cssTiXianServer.deleteWithdrawalAccount(skAppUser);
            if (root != null) {
                String resCode = getNodeValue(root,"respCode");
                if ("0000".equals(resCode)) {
                //解绑第三方
                iSkAppUserService.unbindWithdrawalAccount(req);
                    return R.ok("请求成功");
                }else{
                    throw new RuntimeException(getNodeValue(root,"respDesc"));
                }
            }else {
                throw new RuntimeException("未查询到相关信息");
            }
        }catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    // 辅助方法：获取节点值
    private static String getNodeValue(Element parent, String nodeName) {
        NodeList nodeList = parent.getElementsByTagName(nodeName);
        if (nodeList != null && nodeList.getLength() > 0) {
            Node node = nodeList.item(0);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                return node.getTextContent();
            }
        }
        return "";
    }
}
